package com.java.socket.udp.mulitclient.multithread.receiver;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * @author xzmeasy
 * @version 1.0
 * @since 星期二 十二月,2018
 */
@SuppressWarnings({"Duplicates", "unused"})
public class ReceiverThread implements Runnable {

    private DatagramSocket sendSocket;

    private DatagramSocket receiveSocket;

    public ReceiverThread(DatagramSocket sendSocket, DatagramSocket receiveSocket) {
        this.sendSocket = sendSocket;
        this.receiveSocket = receiveSocket;
    }

    @Override
    public void run() {
        while (true) {
            try {
                // 接收发送方从控制台输入的数据
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                receiveSocket.receive(receivePacket);
                System.out.println("sender: " + new String(receivePacket.getData(), Charset.forName("utf-8")));


//            InputStreamReader inputStreamReader = new InputStreamReader(System.in);
//            BufferedReader reader = new BufferedReader(inputStreamReader);

                // 从控制台输入反馈数据并发送到发送方
                Scanner scanner = new Scanner(System.in);
                String input = scanner.next();
                if ("886".equals(input)) {
                    System.exit(-1);
                }
                byte[] bytes = input.getBytes();
//            String line;
//            while ((line = reader.readLine()) != null) {
//                if ("886".equals(line)) {
//                    break;
//                }
//                byte[] bytes = line.getBytes(Charset.forName("utf-8"));
//                DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length);
//                sendPacket.setAddress(InetAddress.getByName("localhost"));
//                sendPacket.setPort(8889);
//                sendSocket.send(sendPacket);
//            }
                DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length);
                sendPacket.setAddress(InetAddress.getByName("localhost"));
                sendPacket.setPort(8891);
                sendSocket.send(sendPacket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void setSendSocket(DatagramSocket sendSocket) {
        this.sendSocket = sendSocket;
    }

    public void setReceiveSocket(DatagramSocket receiveSocket) {
        this.receiveSocket = receiveSocket;
    }
}
